//
//  RequestService.m
//  WallDetection
//
//  Created by xiebin on 14-12-24.
//  Copyright (c) 2014年 xiebin. All rights reserved.
//

#import "HttpManager.h"
#import "AppDelegate.h"
//#import "EncryptClass.h"
//#define path @"/api_common/"
@implementation HttpManager
+(AFHTTPRequestOperationManager *)sharedHttpManager{
    static AFHTTPRequestOperationManager *managerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        managerInstance = [AFHTTPRequestOperationManager manager];
        managerInstance.responseSerializer = [AFJSONResponseSerializer serializer];//响应为JSON格式
        managerInstance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json",nil];

        managerInstance.requestSerializer = [AFHTTPRequestSerializer serializer];
        //[managerInstance.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];//请求
        managerInstance.requestSerializer.timeoutInterval = 30;
    });
    return managerInstance;
}

+(AFHTTPRequestOperationManager *)requestWithProgressTitle:(NSString *)title method:(NSString*)method path:(NSString*)path paramDict:(NSMutableDictionary*)paramDict  finishBlock:(requestFinishedBlock)finishBlock{
    
    if ([StringUtils isNotNil:title]) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];//背景不能点击
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        [SVProgressHUD setCornerRadius:6];
        [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];//圆圈图形
        [SVProgressHUD showWithStatus:title];
    }
    NSString *finalURL = [NSString stringWithFormat:@"%@/%@",API_HOST,path];
    
    AppDelegate *appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    //    if (appDel.loginMember.UserId) {
    //           [paramDict setObject:appDel.loginMember.UserId forKey:@"UserId"];
    //        //DeLog(@"------userID:%@",appDel.loginMember.UserId);
    //    }
    
    //打印请求URL及参数
    [MyUtility printParams:paramDict andURL:finalURL];
    
    AFHTTPRequestOperationManager *manager = [self sharedHttpManager];
    //manager.requestSerializer.timeoutInterval = 30;
    //[manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];//请求
    //参数设置开始
//    NSString *strParamJson = paramDict ? [paramDict mj_JSONString] : @"";
//    [[self class] setHttpHeaderParams:strParamJson manage:manager];
    //参数设置结束
    
    if([method caseInsensitiveCompare:HTTPS_GET] ==NSOrderedSame){
        
        [manager GET:finalURL parameters:paramDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 DeLog(@"--------responseJson:%@",responseObject);
            if ([StringUtils isNotNil:title]) {
                [SVProgressHUD dismiss];
            }
            finishBlock(responseObject,manager);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                DeLog(@"--------responseError:%@----failInfo:%@",error,operation.responseObject);
            if ([StringUtils isNotNil:title]) {
                [SVProgressHUD dismiss];
            }
            if (operation.responseObject) {
                [WToast showWithText:operation.responseObject[@"Message"]];
            }
        }];
        
    }
    
    else if ([method caseInsensitiveCompare:HTTPS_POST] == NSOrderedSame){
        
        [manager POST:finalURL parameters:paramDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
            DeLog(@"--------responseJson:%@",responseObject);
            if ([StringUtils isNotNil:title]) {
                [SVProgressHUD dismiss];
            }
            finishBlock(responseObject,manager);
            //            //请求成功
            //            NSInteger code = [[responseObject objectForKey:kResCode] integerValue];
            //            switch (code) {
            //
            //                case 200: {
            //                    //成功
            //                    if(finishBlock) finishBlock(responseObject,manager);
            //                    break;
            //                }
            //
            //                default:
            //                    [[NSNotificationCenter defaultCenter]postNotificationName:REQUEST_ERROR_NOTICE object:responseObject userInfo:operation.responseObject];
            //                    break;
            //            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            DeLog(@"--------responseError:%@----failInfo:%@",error,operation.responseObject);
            if ([StringUtils isNotNil:title]) {
                [SVProgressHUD dismiss];
            }
            [[NSNotificationCenter defaultCenter]postNotificationName:REQUEST_ERROR_NOTICE object:error userInfo:operation.responseObject];
        }];
    }
    
    return manager;
}
+(AFHTTPRequestOperationManager *)uploadFileWithProgressTitle:(NSString *)title path:(NSString*)pathName  paramDict:(NSMutableDictionary*)paramDict withDataDic:(NSMutableDictionary *)dataDic extendType:(NSString *)extendType finishBlock:(requestFinishedBlock)finishBlock{
    
    if ([dataDic mt_isEmpty]) return [self requestWithProgressTitle:title method:HTTPS_POST path:pathName paramDict:paramDict finishBlock:finishBlock];
    
    NSString *finalURL = [[NSString stringWithFormat:@"%@/%@",API_HOST ,pathName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manager = [self sharedHttpManager];
    dataDic.count > 0 ? (manager.requestSerializer.timeoutInterval = 60) : (manager.requestSerializer.timeoutInterval = 30);
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];//请求
    //参数设置开始
    [[self class] setHttpHeaderParamsHaveData:paramDict manage:manager];
    //参数设置结束
    
    [manager POST:finalURL parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 一定要在这个block中添加文件参数
        
        NSArray *dataKeys = dataDic.allKeys;
        for (int i=0; i<dataKeys.count; i++){
            NSArray *dataVals = dataDic[dataKeys[i]];
            [dataVals enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *fileName=[NSString stringWithFormat:@"%@.%@",[MyUtility getCurrentDate],extendType];
                
                if ([obj isKindOfClass:[NSData class]]) {
                    [formData appendPartWithFileData:obj name:dataKeys[i] fileName:fileName mimeType:@"application/octet-stream"];
                }else if ([obj isKindOfClass:[UIImage class]]){
                    UIImage *img = (UIImage*)obj;
                    [formData appendPartWithFileData:[[self class] compressOriginalImage:img toMaxDataSizeKBytes:100]  name:dataKeys[i] fileName:fileName mimeType:@"application/octet-stream"];
                }
            }];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (finishBlock) {
            finishBlock(responseObject,manager);
        }
        
        DeLog(@"上传成功----%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[NSNotificationCenter defaultCenter]postNotificationName:REQUEST_ERROR_NOTICE object:error userInfo:operation.responseObject];
    }];
    
    return manager;
}
////设置请求头没有Data的时候
+(void)setHttpHeaderParams:(NSString *)paramsJson manage:(AFHTTPRequestOperationManager*)manager{
    
    // 签名数据
    NSString *sign     = [MD5Util md5:paramsJson];
    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"Sign"];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    // 获取时间戳
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    // 精确到小数点前
    NSString *timeStamp = [NSString stringWithFormat:@"%.0f", a];
    
    [manager.requestSerializer setValue:timeStamp forHTTPHeaderField:@"TimeStamp"];//时间戳
    
    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"PlatformType"];//设备类型
    
    AppDelegate *appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    //[manager.requestSerializer setValue:appDel.loginMember.AccessToken forHTTPHeaderField:@"Token"];//设备类型
    
    
    //    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    //    [manager.requestSerializer setValue:version forHTTPHeaderField:@"AppVersion"];//设备APP版本信息
    
    DeLog(@"Sign === %@",sign);
    DeLog(@"TimeStamp === %@",timeStamp);
    //DeLog(@"Token === %@",appDel.loginMember.AccessToken);
    DeLog(@"body === %@",paramsJson);
}
/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1024;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0) {
        maxQuality = maxQuality - 0.1f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

//设置请求头有Data的时候
+(void)setHttpHeaderParamsHaveData:(NSDictionary *)paramsDic manage:(AFHTTPRequestOperationManager*)manager{
    
    if ([paramsDic mt_isEmpty]) return [self setHttpHeaderParams:@"" manage:manager];
    
    NSArray *arr = paramsDic.allKeys;
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSLiteralSearch|NSWidthInsensitiveSearch|NSForcedOrderingSearch;
    //排序后的结果
    NSArray *resultArray = [arr sortedArrayUsingComparator:^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [[obj1 lowercaseString] compare:[obj2 lowercaseString] options:comparisonOptions range:range];
    }];
    
    NSString *strAppend = @"";
    for (int i=0;i<resultArray.count;i++){
        if (strAppend.length == 0) {
            strAppend = [strAppend stringByAppendingString:[NSString stringWithFormat:@"%@=%@",[resultArray[i] lowercaseString],paramsDic[resultArray[i]]]];
        }else{
            strAppend = [strAppend stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",[resultArray[i] lowercaseString],paramsDic[resultArray[i]]]];
        }
    }
    [self setHttpHeaderParams:strAppend manage:manager];
}


//+(AFHTTPRequestOperationManager *)uploadImageWithPathName:(NSString*)pathName  fileKey:(NSString*)key paramDict:(NSDictionary*)paramDict image:(UIImage *)image imageName:(NSString*)name imageFormat:(NSString *)format  finishBlock:(requestFinishedBlock)finishBlock failBlock:(requestFailedBlock)failBlock
//{
//    NSString *finalURL=[[NSString stringWithFormat:@"%@/%@",domainName,pathName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSData *data=UIImagePNGRepresentation(image);
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
//    // 2.发送请求(做文件上传)
//    // parameters : 只能放非文件参数
//    NSString *userID=[userDefaults objectForKey:@"userID"];
//    NSDictionary *paramsDict=@{@"user_id":userID};
//    //upload_file
//    [manager POST:finalURL parameters:paramsDict
//constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//    // 一定要在这个block中添加文件参数
//
//
//    // 拼接文件参数
//    [formData appendPartWithFileData:data name:key fileName:name mimeType:@"image/png"];
//}
//      success:^(AFHTTPRequestOperation *operation, id responseObject) {
//          if (finishBlock) {
//              finishBlock(responseObject,manager);
//          }
//
//          NSLog(@"上传成功----%@", responseObject);
//      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//          if (failBlock) {
//              failBlock(error);
//          }
//
//          NSLog(@"上传失败----%@", error);
//      }];
//    return manager;
//}

//+(void)downloadFileWithFileURL:(NSString*)fileURL savedPath:(NSString*)savedPath completionHandler:(void (^)(NSURLResponse *response, NSString *filePath, NSError *error))completionBlock
//
//{
//
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//
//    NSURL *URL = [NSURL URLWithString:fileURL];
//    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//
//    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//        NSString *downloadPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",savedPath]];
//        NSFileManager *fileManager=[NSFileManager defaultManager];
//        if (![fileManager fileExistsAtPath:downloadPath]) {
//            [fileManager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil];
//        }
//        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//        //NSURL *documentsDirectoryURL = [NSURL URLWithString:filePath];
//        //MDLog(@"----pathURL: %@", [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:@"download/%@",[response suggestedFilename]]]);
//        MDLog(@"------filen:%@",[response suggestedFilename]);
//        return [documentsDirectoryURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",savedPath,[response suggestedFilename]]];
//    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//        NSString *path=[NSString stringWithFormat:@"/download/%@",[response suggestedFilename]];
//        completionBlock(response,path,error);
//        MDLog(@"File downloaded to: %@", filePath);
//        MDLog(@"----error: %@", error);
//    }];
//    [downloadTask resume];
//
//}
@end

